导航菜单
首页 >  学习Delphi原生JSON框架一 TJsonValue  > 学习Delphi原生JSON框架(二)TJsonArray

学习Delphi原生JSON框架(二)TJsonArray

procedure TForm6.Button1Click(Sender: TObject);var jsonstr:string;

jv:TJSONValue; js:TJSONString; ja:TJSONArray; jo:TJSONObject;

I: Integer;begin jsonstr:='{' +'"person": {' +'"sex": "男",' +'"name": "王小二",' +'"score": [{' +'"语文": 120' +'},' +'{' +'"数学": 89' +'},' +'{' +'"英语": 100' +'}' +']' +'}' +'}';

jv := TJSONValue.ParseJSONValue(jsonstr); //将JSON串转换为JSON对象,即TJSONValue对象 if jv nil then begin

Log('姓名:' + jv.GetValue('person.name').Value); //直接读取节点值Log('性别:' + jv.GetValue('person.sex').Value);Log('成绩');

if jv.TryGetValue('person.score', ja) then //读取JSON对象中的数组对象begin for I := 0 to ja.Count - 1 do //循环数组对象 beginjo := ja.A[I] as TJSONObject; //取数组元素对象var pair:= jo.Pairs[0];//取出Pair对象var s1 := pair.JsonString.value; //读取Pair中键名var s2 := pair.JsonValue.Value; //读取Pair中值//var s2:=jo.Values[s1].Value; //也可以根据Pair的键名读取键值Log(s1 + '=' + s2); end;end;Log(jv.ToString); //输出:{"person":{"sex":"男","name":"王小二","score":[{"语文":120},{"数学":89},{"英语":100}]}}log(jv.ToJSON);//输出:{"person":{"sex":"\u7537","name":"\u738B\u5C0F\u4E8C","score":[{"\u8BED\u6587":120},{"\u6570\u5B66":89},{"\u82F1\u8BED":100}]}} end;

end;

相关推荐: